<?php
class MsgsController extends AppController{
    
    var $name = 'Msgs';
    var $uses = array("Auto_post_handle","User_msg_relationship","Attachment","Msg","Group","CompPerson","CompFinacerelease",'Company','Codetype','User');
    var $helpers = array('Pagination','Html','Javascript','Form','Fck','Str','Action','Accp','Text');
    var $components = array ('Pagination','Session','Cookie');
    var $layout = 'message';
    
    //进入消息提醒系统
    function index(){
        
        App::import('Helper', 'Action');
        $action = new ActionHelper();
        
        //读取用户当前的登录信息
        $user = $this->Session->read('User');
        //var_dump($user);
        $value=array();
        $value1=array();
        //我发的并且有人回复的
        $where='';
        $where.=" Msg.is_deleted='0'  and Msg.owner_id='".$user['id']."' and Msg.has_feedback='1'"; 
        
        $this->Msg->bindModel(array(
            'belongsTo' =>array(
                'User_msg_relationship' => array(
                'conditions' => array("User_msg_relationship.id_two=Msg.id  and  User_msg_relationship.relationship ='message' "),
                // 'fields'  => "distinct(Msg.id)",
                'className'  => 'User_msg_relationship',
                'type' => 'RIGHT',
                'foreignKey' => ''
                )
                
        )));
//        $msgs = $this->Msg->findAll($where,"distinct(Msg.id)","order by Msg.modified desc");
        $msgs = $this->Msg->findAll($where,"distinct(Msg.id)");
        
        foreach($msgs as $msg){
            $value[]=$msg['Msg']['id'];
        }
       

        //获取发给我的消息
        $where='';
        $where.=" Msg.is_deleted='0' "; 
        $this->Msg->bindModel(array(
            'belongsTo' => array(
                'User_msg_relationship' => array(
                'conditions' => array("User_msg_relationship.id_two=Msg.id and User_msg_relationship.id_one='".$user['id']."' and User_msg_relationship.relationship='message'"),
               // 'fields' => "Msg.subject,Msg.content",
                'className'    => 'User_msg_relationship',
                'type'    => 'RIGHT',
                'foreignKey'    => ''
                ),
                'User' => array(
               // 'conditions' => array("User_msg_relationship.id_one=User.id  "),
               // 'fields' => "Msg.subject,Msg.content",
                'className'    => 'User',
               
                'foreignKey'    => 'owner_id'
                )
        )));
       
//        $msgs1=$this->Msg->findAll($where,'distinct(Msg.id)','order by Msg.modified desc');
        $msgs1=$this->Msg->findAll($where,'distinct(Msg.id)');
        
//    var_dump($msgs1);die;
        foreach($msgs1 as $msg1){
            $value1[]=$msg1['Msg']['id'];
        }
        if($value1 || $value){
            $value=array_unique(array_merge($value1,$value));
        }
       
         // var_dump($value);die;
        $this->Msg->bindModel(array(
            'belongsTo' =>array(
                
                'User' => array(
                'conditions' => array("Msg.owner_id=User.id  "),
                // 'fields'  => "Msg.subject,Msg.content",
                'className'  => 'User',
                // 'type'    => 'RIGHT',
                'foreignKey' => ''
                )
        )));
//        $value_str = implode('","', $value);
//		$where_msgs = 'Msg.id in ("'.$value_str.'")';
        $msgs = $this->Msg->findAllById($value);

       //var_dump($msgs); die;
       
        
        //$first_msg= $msgs[0];
      
        if(!empty($this->params['pass'][0])){
           $msg_id=$this->params['pass'][0]; 
            $first_msg=$this->get_msg($msg_id);
            
          //  var_dump($first_msg['Msg']['feedbacks']);die;
            $feedbacks=$first_msg['Msg']['feedbacks'];
           // var_dump($first_msg);die;
            if(!empty($feedbacks)){
                
                foreach($feedbacks as $feedback){
                
                    $this->User_msg_relationship->unbindModel(array ('belongsTo' => array ('Msg')));
                    $this->User_msg_relationship->updateAll(
                        array('User_msg_relationship.is_readed' => "'1'"),
                        array('User_msg_relationship.id_two' => $feedback['Msg']['id'],'User_msg_relationship.id_one' =>$msg_id,'User_msg_relationship.relationship' =>'feedback',"User_msg_relationship.user_id"=>$user['id'])
                    );
                    // var_dump($feedbacks);die;
                }
            }
           
            $this->User_msg_relationship->unbindModel(array ('belongsTo' => array ('Msg')));
            $this->User_msg_relationship->updateAll(
                array('User_msg_relationship.is_readed' => "'1'"),
                array('User_msg_relationship.id_two' => $msg_id,'User_msg_relationship.id_one' =>$user['id'],'User_msg_relationship.relationship' =>'message')
            );
            if($user['id']==$first_msg['Msg']['owner_id']){
                $this->Msg->id=$msg_id;
                $this->Msg->saveField('is_readed','1');
            }
        }else{
            
           if($msgs[0]['Msg']['id']){
                $first_msg=$this->get_msg($msgs[0]['Msg']['id']);
            }
        }
       
        $msgs=$this->feedbacks($msgs);
     //  var_dump($msgs);
    //   echo "<br>";
        foreach($msgs as $key=>$msg){
            
            if($msg['User']['cid'] != null || $msg['User']['cid'] != ''){
                $comp=$this->Company->findById($msg['User']['cid']);
               
                $msgs[$key]['User']['name']=$comp['Company']['company_name'];
                $msgs[$key]['User']['id']=$comp['Company']['id'];
            }
        }
       // var_dump($first_msg);die;
       
        //切换到写消息时左侧不动
        $this->Session->write('Msgs', $msgs);
        $current_menu = 'idx';
        $this->set(compact('current_menu','msgs','first_msg'));
        
    }
    
    //系统消息
    function system_msg(){
        //App::import('Helper', 'Action');
        //$this->redirect(array('action' => 'sys_msg'));
        $user = $this->Session->read('User');
        //var_dump($user);
        
 

        //获取系统所有消息
        $where='';
        $where.=" Msg.is_deleted='0'"; 
        $this->Msg->bindModel(array(
            'belongsTo' => array(
                'User_msg_relationship' => array(
                'conditions' => array("User_msg_relationship.id_two=Msg.id and User_msg_relationship.id_one='".$user['id']."' and User_msg_relationship.relationship='sys'"),
               // 'fields' => "Msg.subject,Msg.content",
                'className'    => 'User_msg_relationship',
                'type'    => 'RIGHT',
                'foreignKey'    => ''
                ),
                'User' => array(
              //  'conditions' => array("User_msg_relationship.id_one=User.id  "),
               // 'fields' => "Msg.subject,Msg.content",
                'className'    => 'User',
                
                'foreignKey'    => 'owner_id'
                ),
        )));
       
        $msgs=$this->Msg->findAll($where,'Msg.*,User.*');
      
        if(!empty($this->params['pass'][0])){
           $msg_id=$this->params['pass'][0]; 
            
            $first_msg=$this->get_msg($msg_id);
            
            $this->User_msg_relationship->unbindModel(array ('belongsTo' => array ('Msg')));
            $this->User_msg_relationship->updateAll(
                array('User_msg_relationship.is_readed' => "'1'"),
                array('User_msg_relationship.id_two' => $msg_id,'User_msg_relationship.id_one' =>$user['id'],'User_msg_relationship.relationship' =>'sys')
            );
            if($user['id']==$first_msg['Msg']['owner_id']){
                $this->Msg->id=$msg_id;
                $this->Msg->saveField('is_readed','1');
            }
            
        }else{
            if($msgs[0]['Msg']['id']){
                $first_msg=$this->get_msg($msgs[0]['Msg']['id']);
            }
            
        }
      //  var_dump($msgs);die;
       
        $this->Session->write('Msgs', $msgs);
        
        $current_menu = 'sys';
        $this->set(compact('current_menu','msgs','first_msg'));
        
    }
    
    function getMonthNum( $date1, $date2, $tags='-' ){
        
      $date1 = explode($tags,$date1);
      $date2 = explode($tags,$date2);
      return abs($date1[0] - $date2[0]) * 12 + abs($date1[1] - $date2[1]);
    }
     //自动发送系统消息
    function auto_post(){
        $this->layout=false;
        $params=array('conditions' => array('Auto_post_handle.enabled' => '1'));
        $lists = $this->Auto_post_handle->find("all",$params);
      // var_dump(3);
        $post_list=array();
        foreach($lists as $list){
            
            $today=date('Y-m',strtotime("now"));
       // strtotime('+1 month', time()); // 下个月
            $interval=$list['Auto_post_handle']['interval'];
          //  var_dump((int)$interval);
            $start_date=date('Y-m', strtotime('+'.$interval.' month', $list['Auto_post_handle']['start_date']));
        //    $start_date=date('Y-m-d', ($list['Auto_post_handle']['start_date']));
          //  var_dump($today);
         //   var_dump($start_date);
          //两日期相差多少月
           // $interval_mouth=$this->getMonthNum($today,$start_date);
            //和间隔月数比较,整除就代表要发送
          //  echo $interval_mouth;
          ///  if($interval_mouth % $interval==0){
          //      $post_list[]=$list['Auto_post_handle']['msg_id'];
           // }
            
            if($today==$start_date){
                //echo 33;
                $post_list[]=$list['Auto_post_handle']['msg_id'];
                $this->Auto_post_handle->id=$list['Auto_post_handle']['id'];
                $this->Auto_post_handle->saveField('interval',$interval*2);
            }
           
        }
       
        // var_dump($post_list);die;
         
      /*   if($post_list){
                foreach ($post_list as $pid){
                    $pidlist.="'".$pid."',";
                }
            }
            $wheres=rtrim($pidlist,",");	
            if(empty($wheres)){
                $wheres=1;
            }*/
         if($post_list){  
             foreach($post_list as $pid){
                 $msg=$this->Msg->findById($pid);
                  
                 $option['subject']=$msg['Msg']['subject'];
                 $option['content']=$msg['Msg']['content'];
                 $option['auto_sys']='1';
                 $option['owner_id']=$msg['Msg']['owner_id'];
                 $option['is_readed']='1';
               
                 $this->Msg->saveAll($option);   
                 $msg_id=$this->Msg->getLastInsertId();   
 //var_dump($msg['Msg']['id']);die;                 
                 //$sql = "insert into msgs (`id`,`subject`,`content`,`owner_id`,is_readed,created,modified) SELECT UUID(),`subject`,`content`,`owner_id`,'1',now(),now() from msgs where id = '".$pid."' ";
                  $sql = "insert into user_msg_relationships (`id`,`id_one`,`relationship`,`id_two`,created,modified) SELECT UUID(),`id_one`,`relationship`,'".$msg_id."','".date('Y-m-d H:i:s')."','".date('Y-m-d H:i:s')."' from user_msg_relationships where id_two ='".$msg['Msg']['id']."' ";
              
            //     $relationship['id_one']=$msg['Msg']['subject'];
             //    $relationship['relationship']=$msg['Msg']['content'];
            //     $relationship['id_two']=$msg['Msg']['owner_id'];
            //     $relationship['is_readed']='1';
               
            //     $this->Msg->saveAll($relationship);   
                  
                    $this->User_msg_relationship->query($sql);
                    
                    $this->mylog($msg_id,'自动发送成功');
                  //  $res=last_insert_id();
                  // exit;
             }
         }
        // exit;
        
        
       
    }
    //日志
    function mylog($id,$desc) {
        
        //记录日志
        $dir="../tmp/logs/postlog.txt";
        //判断文件存在否		
        $fp = fopen($dir,'ab'); //以二进制追加方式打开文件,没文件就创建 		
        $col =date('Y-m-d H:i:s')."  msg[id:".$id." desc:".$desc."] \r\n"; //记录赋值 		
        fwrite($fp, $col, strlen($col)); //插入第一条记录 
        fclose($fp); //关闭文件 			
      //  echo "      \r\n<br/>".$col;
    }
    //定时执行服务进程
    function post_handle(){
        
        ignore_user_abort(); // 函数设置与客户机断开是否会终止脚本的执行
        set_time_limit(0); // 来设置一个脚本的执行时间为无限长
        $interval=10*60*60;
       
        do{
             
            $this->auto_post();
           // echo 3;
        // $fp = fopen('text3.txt','a');
       //  fwrite($fp,'test');
        // fclose($fp);
         
            sleep($interval); // 函数延迟代码执行若干秒
        }while(true);
    }
    
    //发件箱
    function outbox(){
        
        $user = $this->Session->read('User');
        
        $where='';
        $where.=" Msg.is_deleted='0' and Msg.auto_sys='0' and Msg.owner_id='".$user['id']."' and Msg.has_feedback='0'"; 
        
        $this->Msg->bindModel(array(
            'belongsTo' =>array(
                'User_msg_relationship' => array(
                'conditions' => array("User_msg_relationship.id_two=Msg.id  and  (User_msg_relationship.relationship ='message' or User_msg_relationship.relationship ='sys')"),
                // 'fields'  => "distinct(Msg.id)",
                'className'  => 'User_msg_relationship',
                'type' => 'RIGHT',
                'foreignKey' => ''
                )
                
        )));
        $msgs = $this->Msg->findAll($where,"distinct(Msg.id)");
        foreach($msgs as $msg){
            $value[]=$msg['Msg']['id'];
        }
       
        
        $this->Msg->bindModel(array(
            'belongsTo' =>array(
                
                'User' => array(
                'conditions' => array("Msg.owner_id=User.id  "),
                // 'fields'  => "Msg.subject,Msg.content",
                'className'  => 'User',
                // 'type'    => 'RIGHT',
                'foreignKey' => ''
                )
        )));
        
        $msgs = $this->Msg->findAllById($value);
        // var_dump($msgs);die;
        if(!empty($this->params['pass'][0])){
            $msg_id=$this->params['pass'][0]; 
            $first_msg=$this->get_msg($msg_id);
            
            if($user['id']==$first_msg['Msg']['owner_id']){
                $this->Msg->id=$msg_id;
                $this->Msg->saveField('is_readed','1');
            }
        }else{
            if($msgs[0]['Msg']['id']){
                $first_msg=$this->get_msg($msgs[0]['Msg']['id']);
            }
        }
        
        foreach($msgs as $key=>$msg){
            
            if($msg['User']['cid'] != null || $msg['User']['cid'] != ''){
                $comp=$this->Company->findById($msg['User']['cid']);
               
                $msgs[$key]['User']['name']=$comp['Company']['company_name'];
                $msgs[$key]['User']['id']=$comp['Company']['id'];
            }
            
            $params=array('conditions' => array('Auto_post_handle.enabled' => '1','Auto_post_handle.msg_id'=>$msg['Msg']['id']));
            $lists = $this->Auto_post_handle->find("all",$params);
           // var_dump($msgs);
            if($lists){
               // var_dump($lists);
                $msgs[$key]['istime']='1';
                
            }
            
        }
        if($first_msg){
           
            $params=array('conditions' => array('Auto_post_handle.enabled' => '1','Auto_post_handle.msg_id'=>$first_msg['Msg']['id']));
            $lists = $this->Auto_post_handle->find("first",$params);
           // var_dump($msgs);
            if($lists){
               // var_dump($lists);
                $first_msg['istime']='1';
                $first_msg['interval']=$lists['Auto_post_handle']['interval'];
            }
            // var_dump($first_msg);die;
        }
        
        //var_dump($msgs);die;
        $msgs=$this->feedbacks($msgs);
        $this->Session->write('Msgs', $msgs);
        $current_menu = 'out';
        $this->set(compact('current_menu','msgs','first_msg'));		
    }
    
    //写消息
    function write(){
        $this->layout=false;
        $msgs = $this->Session->read('Msgs');
        $where = '';
        $where.= "(Group.is_deleted='0')";
        $this->Group->bindModel(array('hasMany'=>array('User'=>array('conditions' => array("User.is_deleted='0' "),
            'fields' =>  "id, name",
            'className'    => 'User',
            'order' => 'id ASC',
            'foreignKey'    => 'groupid'))));
        $groups = $this->Group->findAll($where,'id, group_name');
        
        $where ='';
        $where.="(Company.is_deleted='0')";
        $this->Company->unbindModel(array('hasMany'=>array('pros_cvalue','Attachment','CompType','CompTalent','CompFinacerelease')));
        $sqlStr = "select distinct companies.id, companies.company_name from companies inner join users as u on u.cid = companies.id where u.is_deleted = '0' and companies.is_deleted = '0'";
        $companies = $this->Company->query($sqlStr);
        
        $current_menu = 'wrt';
      /*  if(!empty($this->params['pass'][0])){
           $msg_id=$this->params['pass'][0]; 
           $first_msg=$this->get_msg($msg_id);
        }*/
        
        $msg_type=!empty($_POST['msg_type'])?$_POST['msg_type']:null;
        
        $this->set(compact('current_menu','msgs','first_msg','groups','companies','msg_type'));
      /*  if(!empty($this->params['pass'][0])){
             $this->render('/msgs/index');
        }*/
       echo $this->render('/msgs/write');
       exit;
    }
    
    function cancel_auto_post($id){
       //var_dump($id);die;
        if($id){
           
          $res=$this->Auto_post_handle->findByMsgId($id);
        //  var_dump($res['Auto_post_handle']['id']);die;
          $this->Auto_post_handle->id=$res['Auto_post_handle']['id'];
          $this->Auto_post_handle->saveField('enabled','0');
          $this->Session->setFlash('取消成功');
          $this->redirect(array('action' => 'outbox'));  
        }else{
            $this->Session->setFlash('取消失败');
          $this->redirect(array('action' => 'outbox'));  
        }
        
    }
    
    function add(){
    	
        // var_dump($_POST['msg_type']);die;
        $log_user = $this->Session->read('User');
        
        if(empty($_POST['feedback'])){
            if(empty($_POST['users']) && empty($_POST['coms'])){
                $this->Session->setFlash('发送失败','default',array('class' => 'info_error_alert'));
                die;
            }
        }
        
        if(empty($_POST['feedback'])){
            if(!empty($_POST['users'])){
                $users=$_POST['users'];
                
            }
        }else{
            if(!empty($_POST['feed_users'])){
                $users=$_POST['feed_users'];
                
            }
        }
        
        //var_dump($_POST);die;
        
        
        
        if(!empty($_POST['coms'])){
            $coms=$_POST['coms'];
            $datas=$this->User->findAllByCid($coms);
            
            foreach($datas as $data){
                $users[]=$data['User']['id'];
            }
        }
        
        $users=array_unique($users);
       
        
        if(empty($_POST['feedback'])){
            $msg['subject']=$_POST['subject'];
            $msg['content']=$_POST['content'];
            $msg['is_readed']='1';
            
        }else{
            $msg['subject']=$_POST['feedback_msg'];
            $msg['content']=$_POST['feedback_msg'];
            $msg['is_readed']='0';
        }
        
        $msg['owner_id']=$log_user['id'];
           
        if($this->Msg->save($msg)){
           //var_dump($msg);die;
            //message类型
            if(empty($_POST['feedback'])){
                foreach($users as $user){
                
                    $relationship['id_one']=$user;
                   
                    if($_POST['msg_type']=='sys'){
                        $relationship['relationship']='sys';
                    }else if($_POST['msg_type']=='message'){
                        $relationship['relationship']='message';
                    }
                    
                    $relationship['id_two']=$this->Msg->id;  
                         
                    $this->User_msg_relationship->saveAll($relationship);               
                }
                
                if(!empty($_POST['fixed_time']) && !empty($_POST['month_opt']) && ($_POST['fixed_time']=='1')){
                 
                   $month_opt=$_POST['month_opt'];
                   $params1['msg_id'] =$this->Msg->id;
                   $params1['start_date'] =time();
                   $params1['interval'] =$month_opt;
                   $params1['enabled'] ='1';
                   $this->Auto_post_handle->saveAll($params1);
                }
            }else{
                //回复类型
              //  var_dump(array_search($log_user['id'],$users));
              //  unset($users[array_search($log_user['id'],$users)]);
              
              $msg1=$this->Msg->findById($_POST['feedback']);

                $users[]=$msg1['Msg']['owner_id'];
                foreach($users as $key=>$user){
                    $res=$this->User->findAllByCid($user);
                    if($res){
                       foreach($res as $re){
                          $users[] = $re['User']['id'];
                       }
                       unset($users[$key]);
                    }
                    
                }
              // var_dump($users); die;
                $users=array_unique($users);
                
                foreach($users as $user){
                    
                    $relationship['id_one']=$_POST['feedback'];
                    $relationship['relationship']='feedback';
                    $relationship['id_two']=$this->Msg->id;  
                    //回复的接受者
                    $relationship['user_id']=$user;  
                         
                    $this->User_msg_relationship->saveAll($relationship); 
                    
                    $this->User_msg_relationship->unbindModel(array ('belongsTo' => array ('Msg')));
                    $this->User_msg_relationship->updateAll(
                        array('User_msg_relationship.is_readed' => "'0'"),
                        array('User_msg_relationship.id_two' => $_POST['feedback'],'User_msg_relationship.id_one' =>$user,'User_msg_relationship.relationship' =>'message')
                    );
                }
                
                $this->Msg->id=$_POST['feedback'];
                $this->Msg->saveField('is_readed','0');
                $this->Msg->saveField('has_feedback','1');
                $this->Msg->saveField('modified',date('Y-m-d H:i:s',time()));
            }
            
           
            if(!empty($_POST['upload'])){
                $uploads=$_POST['upload'];
               // var_dump($uploads);
                $this->Attachment->updateAll(
                    array('Attachment.pid' => "'".$this->Msg->id."'"),
                    array('Attachment.id' => $uploads)
                );
            }
            
           
            if(empty($_POST['feedback'])){
                $this->Session->setFlash('发送成功');
                $this->redirect('/msgs/outbox/'.$this->Msg->id);
            }else{
                $this->Session->setFlash('回复成功');
                $this->redirect(array('action' => 'index/'.$_POST['feedback']));
            }
            
        }
    }
    
    function show_msg(){
        
       // var_dump($_GET);
       // var_dump($this->params['pass'][0]);
        $msg_id=$this->params['pass'][0];
        $this->index($msg_id);
       // $current_menu = 'idx';
      //  $this->set(compact('current_menu'));		
    }
    
    //获得消息内容
    function get_msg($msg_id){
         $cuser=$this->Session->read('User');
        $where='';
        $where.="Msg.id='".$msg_id."'"; 
        $this->Msg->bindModel(array(
            'belongsTo' => array(
                
               
                'User' => array(
                'conditions' => array("Msg.owner_id=User.id  "),
               // 'fields' => "User.name",
                'className'    => 'User',
               
                'foreignKey'    => ''
                )
               
        )));
        $msg=$this->Msg->findAll($where);
       
        $where='';
        $where.="User_msg_relationship.id_two='".$msg_id."' "; 
        $this->User_msg_relationship->bindModel(array(
            'belongsTo' => array(
                
                'User' => array(
                'conditions' => array("User_msg_relationship.id_one=User.id  "),
               // 'fields' => "User.name",
                'className'    => 'User',
               
                'foreignKey'    => ''
                ),
                'User' => array(
                'conditions' => array("User_msg_relationship.id_one=User.id  "),
               // 'fields' => "User.name",
                'className'    => 'User',
               
                'foreignKey'    => ''
                )
               
        )));
        
        $id_ones=$this->User_msg_relationship->findAll($where,'User.*');
        //var_dump($id_ones);die;
        $new_one=array();
        $aa=0;
        foreach($id_ones as $id_one){
            if($id_one['User']['cid'] != null || $id_one['User']['cid'] != ''){
                $comp=$this->Company->findById($id_one['User']['cid']);
               
                $new_one[$aa]['name']=$comp['Company']['company_name'];
                $new_one[$aa]['id']=$comp['Company']['id'];
            }else{
                $new_one[$aa]['name']=$id_one['User']['name'];
                $new_one[$aa]['id']=$id_one['User']['id'];
            }
           
            $aa++;
        }
        
        $id_ones=array();
        foreach ($new_one as $v){  
          $v = join(",",$v);  //降维,也可以用implode,将一维数组转换为用逗号连接的字符串  
          $temp[] = $v;  
        }  
   // var_dump($new_one);
       
        $temp = array_unique($temp);    //去掉重复的字符串,也就是重复的一维数组  
        foreach ($temp as $k => $v){  
            $com=explode(",",$v);
            $id_ones[$k]['name'] = $com[0];   //再将拆开的数组重新组装  
            $id_ones[$k]['id'] = $com[1];   //再将拆开的数组重新组装  
            
        }  
       // $id_ones = $temp;  
        $id_ones=array_slice($id_ones,0);
     //  var_dump($id_ones); die;
        $where='';
        $where.="Attachment.pid='".$msg_id."' and Attachment.is_deleted='0'"; 
        $attachments=$this->Attachment->findAll($where,'Attachment.*');
       // var_dump($attachments);die;
       
        $pagesize=10;
        $paging['show']=$pagesize;
        $paging['url'] = '/msgs/index/'.$msg_id;
        $urlcount=0;
        
        
       
        
        
        $where='';
        $where.=" Msg.is_deleted='0'"; 
        $this->Msg->bindModel(array(
            'belongsTo' => array(
                'User_msg_relationship' => array(
                'conditions' => array("User_msg_relationship.id_two=Msg.id and User_msg_relationship.id_one='".$msg_id."' and User_msg_relationship.relationship='feedback' and  `User_msg_relationship`.user_id ='".$cuser['id']."'"),
               // 'fields' => "Msg.subject,Msg.content",
                'className'    => 'User_msg_relationship',
                'type'    => 'RIGHT',
                'foreignKey'    => ''
                ),
                'User' => array(
               // 'conditions' => array("User_msg_relationship.id_one=User.id  "),
               // 'fields' => "Msg.subject,Msg.content",
                'className'    => 'User',
               
                'foreignKey'    => 'owner_id'
                ),
        )));
        
        $urlcount=$this->Msg->findCount($where);
     //   var_dump($urlcount);die;
      
        
        $paging['total'] =$urlcount;
        $showpage=0;
        $this->Msg->bindModel(array(
            'belongsTo' => array(
                'User_msg_relationship' => array(
                'conditions' => array("User_msg_relationship.id_two=Msg.id and User_msg_relationship.id_one='".$msg_id."' and User_msg_relationship.relationship='feedback' and  `User_msg_relationship`.user_id ='".$cuser['id']."'"),
               // 'fields' => "Msg.subject,Msg.content",
                'className'    => 'User_msg_relationship',
                'type'    => 'RIGHT',
                'foreignKey'    => ''
                ),
                'User' => array(
               // 'conditions' => array("User_msg_relationship.id_one=User.id  "),
               // 'fields' => "Msg.subject,Msg.content",
                'className'    => 'User',
               
                'foreignKey'    => 'owner_id'
                ),
        )));

        $feedbacks = "";
        if ($paging['total'] > 0) {
            list ($order, $limit, $page) = $this->Pagination->init("", $paging);
            $feedbacks=$this->Msg->findAll($where,'Msg.*,User.*','Msg.created desc',$limit,$page);
           // var_dump($feedbacks);die;
            if($urlcount>$pagesize)
            {
                $showpage=1;
            }
        }
        
        if($msg[0]['User']['cid'] != null || $msg[0]['User']['cid'] != ''){
            $comp=$this->Company->findById($msg[0]['User']['cid']);
           
            $msg[0]['User']['name']=$comp['Company']['company_name'];
            $msg[0]['User']['id']=$comp['Company']['id'];
        }
        
        if(!empty($feedbacks)){
            foreach($feedbacks as $key=>$feedback){
            
                if($feedback['User']['cid'] != null || $feedback['User']['cid'] != ''){
                    $comp=$this->Company->findById($feedback['User']['cid']);
                   
                    $feedbacks[$key]['User']['name']=$comp['Company']['company_name'];
                    $feedbacks[$key]['User']['id']=$comp['Company']['id'];
                }
            }
        }
      //  var_dump($id_ones);die;
        
        $msg[0]['Msg']['id_ones']=$id_ones;
        $msg[0]['Msg']['attachments']=$attachments;
        $msg[0]['Msg']['feedbacks']=$feedbacks;
        $msg[0]['Msg']['feedbacksShowpage']=$showpage;
      //  var_dump($msg[0]);die;
        return $msg[0];
    }
    
    //获得消息回复数
    function feedbacks($msgs){
        $i=0;
        $cuser=$this->Session->read('User');
        //var_dump($msgs);die;
        foreach($msgs as $msg){
            
            $sql= "select count(Msg.id) as feedback_count from `msgs` AS `Msg` where  `Msg`.`id` in (select User_msg_relationship.id_two from `msgs` AS `Msg` RIGHT JOIN `user_msg_relationships` AS `User_msg_relationship` ON (`User_msg_relationship`.`is_readed`='0' and   `User_msg_relationship`.`id_one`=`Msg`.`id` and `User_msg_relationship`.`relationship`='feedback' and `User_msg_relationship`.user_id = '".$cuser['id']."') where  `Msg`.`id`='".$msg['Msg']['id']."')";
            $un_c= $this->Msg->query($sql);
         //   var_dump($un_c[0][0]);die;
            $msgs[$i]['Msg']['feedback_count']=$un_c[0][0]['feedback_count'];
            $i++;
        }
      //  die;
        return $msgs;
    }
    
    function ajax_get_count(){
        // echo 333;exit;
        $cuser=$this->Session->read('User');
        if($cuser){
             //获取收件箱未读消息条数
           $unread_count=$this->get_unread_count($cuser['id']);
            
            //获取系统未读消息条数
            $unread_sys_count=$this->get_unread_sys_count($cuser['id']);
            
            //获取发件箱未读消息条数
           // $unread_re_count=$this->get_unread_re_count($cuser['id']);
            echo json_encode($unread_count+$unread_sys_count);
            exit;
        }else{
           //$this->redirect($this->referer());
            exit;
        }
       
    }
    
    //获取发件箱未读消息条数
    function get_unread_re_count($user_id){
        $user = $this->Session->read('User');
       // var_dump($user);
        $where='';
       $where.=" Msg.is_deleted='0' and Msg.is_readed='0'  and Msg.owner_id='".$user['id']."' and Msg.has_feedback='1'"; 
        
        $this->Msg->bindModel(array(
            'hasMany' =>array(
                'User_msg_relationship' => array(
                'conditions' => array("User_msg_relationship.id_two=Msg.id  and  User_msg_relationship.relationship ='message' "),
                // 'fields'  => "distinct(Msg.id)",
                'className'  => 'User_msg_relationship',
                'type' => 'RIGHT',
                'foreignKey' => ''
                )
                
        )));
        
        $unread_re_count=$this->Msg->findCount($where,"distinct(Msg.id)");
      //  var_dump($unread_re_count);die;
        return $unread_re_count;
    }
    
    
    //获取收件箱未读消息条数
    function get_unread_count($user_id){
       // $user = $this->Session->read('User');
        //var_dump($user);
        
        $where=" Msg.is_deleted='0'  "; 
        $this->Msg->bindModel(array(
            'belongsTo' => array(
                'User_msg_relationship' => array(
                'conditions' => array("User_msg_relationship.is_readed='0' and  User_msg_relationship.id_two=Msg.id and User_msg_relationship.id_one='".$user_id."' and User_msg_relationship.relationship='message'"),
               // 'fields' => "Msg.subject,Msg.content",
                'className'    => 'User_msg_relationship',
                'type'    => 'RIGHT',
                'foreignKey'    => ''
        ))));
        $unread_count=$this->Msg->findCount($where);
        
      //  $where=" Msg.is_deleted='0' and Msg.is_readed='0'  and Msg.owner_id='".$user_id."'"; 
        
       // $unread_re_count=$this->Msg->findCount($where);
        //die;
        $unread_re_count=$this->get_unread_re_count($user_id);
   // var_dump($unread_re_count);die;
        return $unread_count+$unread_re_count;
    }
    
    //获取系统未读消息条数
    function get_unread_sys_count($user_id){
        
        $where='';
        $where.=" Msg.is_deleted='0'"; 
        $this->Msg->bindModel(array(
            'belongsTo' => array(
                'User_msg_relationship' => array(
                'conditions' => array("User_msg_relationship.is_readed='0' and  User_msg_relationship.id_two=Msg.id and User_msg_relationship.id_one='".$user_id."' and User_msg_relationship.relationship='sys'"),
               // 'fields' => "Msg.subject,Msg.content",
                'className'    => 'User_msg_relationship',
                'type'    => 'RIGHT',
                'foreignKey'    => ''
        ))));
        $unread_sys_count=$this->Msg->findCount($where);
       
        return $unread_sys_count;
    }
    
    function download($id)
    {
        $attachments=$this->Attachment->findById($id);
        $file_title=$attachments["Attachment"]["file_name"];
        $path=$attachments["Attachment"]["file_path"];
        App::import('Helper', 'Action');
        $actionf = new ActionHelper();
        $actionf->downloads($file_title,$path);
        exit();
    }
    
    function upload(){
       
        if(!empty($_FILES['upload']['name'])){
                    
            $user_id=$this->User->id;
            App::import('Helper', 'Action');
            $actionf = new ActionHelper();
        
            //$photo=$this->data["Company"]["photo"];
            $file=$_FILES['upload'];
            
            $dirpath="upload/files/";
            if(!is_dir($dirpath)){
                mkdir($dirpath, 0777, true);
            }
            $imgpath=$actionf->upload_file($file,$dirpath,0);
           

            
            $attachment['file_name']=$_FILES['upload']['name'];
            $attachment['file_path']=$dirpath.$imgpath;
           
            if($this->Attachment->save($attachment)){
                
                $attachment['file_id']=$this->Attachment->id;
                echo  json_encode($attachment);
                
            }

            
        }
        exit;
    }
    
     //打开页面前执行的方法
    function beforeFilter()
    {
        parent::beforeFilter();
        $cuser=$this->Session->read('User');
        if (!$cuser){
            $this->redirect('/users/login');
            exit;
        }
        
       
    }
    
    function beforeRender(){
        
        $cuser=$this->Session->read('User');
        //获取收件箱未读消息条数
        $unread_count=$this->get_unread_count($cuser['id']);
        
        //获取发件箱未读消息条数
      //  $unread_re_count=$this->get_unread_re_count($cuser['id']);
        
        
        
        //获取系统未读消息条数
        $unread_sys_count=$this->get_unread_sys_count($cuser['id']);
        //var_dump($unread_count);die;
        $this->set(compact('unread_count','unread_sys_count'));
    }
}
?>